#pragma once

#include "Connection.hpp"
#include "HandlerConnection.hpp"
#include "Log.hpp"

class Accepter // 连接管理器
{
public:
    Accepter() {}

    // ET模式下，我们并不能确认只有一个连接到来，所以这里需要循环判断
    void AccepterConnection(Connection *conn)
    {
        errno = 0;
        
        while (true)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

            int sockfd = accept(conn->GetSockfd(), (sockaddr *)&client, &len);
            if (sockfd >= 0)
            {
                lg.LogMessage(Info, "get a new link , sockfd : %d\n", sockfd);

                auto reader = bind(&HandlerConnection::Reader,placeholders::_1);
                auto writer = bind(&HandlerConnection::Writer,placeholders::_1);
                auto excepter = bind(&HandlerConnection::Excepter,placeholders::_1);

                Connection *new_conn = ConnectionFactory::BuildNormalConnection(sockfd, EPOLLIN | EPOLLET, reader, writer, excepter,conn->_R);
                conn->_R->AddConnection(new_conn);
            }
            else
            {
                if (errno == EAGAIN)
                {
                    break;
                }
                else if (errno == EINTR)
                {
                    continue;
                }
                else
                {
                    lg.LogMessage(Warning, "get a new link error\n");
                    break;
                }
            }
        }
    }

    ~Accepter()
    {
    }
};